<template>
  <section class="map__container" :id="mapId">
    <map-toolbar ref="mapToolbar"
                 :isTools="isTool"
                 :isShowData="isShowData"
                 :keyss="keys"
                 :isSearch="isSearch"
                 @switchShow="switchShow"
                 @handleSearch="handleSearch"
                 @start-map-select="startMapSelect"
                 @cancel-map-select="cancelMapSelect">
      <template slot="beforeToolbarItem">
        <slot name="beforeToolbarItem"></slot>
      </template>
      <template slot="beforeDropdownItem">
        <slot name="beforeDropdownItem"></slot>
      </template>
      <template slot="afterDropdownItem">
        <slot name="afterDropdownItem"></slot>
      </template>
      <template slot="afterToolbarItem">
        <slot name="afterToolbarItem"></slot>
      </template>

      <el-button v-if="mapPosition"
                 class="map__position"
                 type="text"
                 @click="handleCurrentPosition">
        <d2-icon name="bullseye" style="font-size: 18px;"/>
      </el-button>
    </map-toolbar>
  </section>
</template>
<script>
  import mapToolbar from './components/map-toolbar'
  import mapTab from './components/map-tab'
  import mapPoiSearch from './components/map-poi-search'
  import { TyMap, TyHelper, TyFeatureLayer } from '@/plugin/map/tyMapUtlis'
  import GeoJSON from 'ol/format/GeoJSON'
  import 'ol/ol.css'
  import { MarkerMixin } from './mixins/markerMixin'
  import { mapGetters } from 'vuex'
  import $ from 'jquery'
  import { validatenull } from '@/utils/validate'

  export default {
    name: 'common-map',
    mixins: [MarkerMixin],
    provide() {
      return {
        commonMap: this
      }
    },
    components: {
      'map-toolbar': mapToolbar,
      'map-tab': mapTab,
      'map-poi-search': mapPoiSearch
    },
    props: {
      keys: {
        type: String,
        default: ''
      },
      // 是否显示人员,案件,车辆,视频的详情页面
      isSearch: {
        type: Boolean,
        default: false
      },
      // 点击兴趣点相关参数
      clickPoi: {
        type: Object,
        default: () => {
          return {
            // 点击兴趣点关闭列表
            closePoiList: false,
            // 点击兴趣点是否显示详情
            showPoiInfo: true,
            // 是否显示标题
            showPoiTitle: true,
            // 是否调用地图点击方法
            mapClick: false
          }
        }
      },
      // 是否显示人员,案件,车辆,视频的详情页面
      detailVisible: {
        type: Boolean,
        default: false
      },
      // 人员,案件,车辆,视频图层禁止选择选项
      toolbarDisabledOption: {
        type: Object,
        default: () => {
          return {
            staff: false,
            case: false,
            car: false,
            video: false
          }
        }
      },
      // 是否使用默认框选
      defaultSelection: {
        type: Boolean,
        default: false
      },
      toolbarSelectVisible: {
        type: Boolean,
        default: false
      },
      tabVisible: {
        type: Boolean,
        default: false
      },
      poiVisible: {
        type: Boolean,
        default: true
      },
      // 案件图层
      caseLayer: {
        type: Boolean,
        default: false
      },
      // 监督员图层
      staffLayer: {
        type: Boolean,
        default: false
      },
      carLayer: {
        type: Boolean,
        default: false
      },
      // 车辆电子围栏图层
      carFenceLayer: {
        type: Boolean,
        default: false
      },
      // 视频图层
      videoLayer: {
        type: Boolean,
        default: false
      },
      // 是否需要开启地图遮罩层
      mapLoading: {
        type: Boolean,
        default: false
      },
      // 是否显示工具箱
      isTool: {
        type: Boolean,
        default: false
      },
      isShowData: {
        type: Boolean,
        default: false
      },
      // 是否显示定位图标
      mapPosition: {
        type: Boolean,
        default: false
      },
      startDragBoxHandler: Function,
      endDragBoxHandler: Function,
      // 要显示图层ID结合
      wmsIds: {
        type: Array,
        default: () => {
          return []
        }
      },
      wmsGridData: {
        type: Array,
        default: () => {
          return []
        }
      },
      districtGridData: {
        type: Array,
        default: () => {
          return []
        }
      },
      // 图层类型
      // district 区域网格 street 街道网格 comm 社区网格 unit 单元网格 work 工作网格
      // area_work 区域网格加工作网格 wh_parts 部件图层  mph_poi_road 兴趣点门牌号道路
      wmsIdsType: {
        type: String
      },
      wmsIdsStyles: {
        type: String,
        default: () => {
          return ''
        }
      }
    },
    data() {
      return {
        map: null,
        option: null,
        helper: null,
        // 案件社区网格图层与标记
        eventObject: {
          marker: null,
          highlightFeatureLayer: null
        },
        caseLayerLocal: this.caseLayer,
        staffLayerLocal: this.staffLayer,
        carLayerLocal: this.carLayer,
        carFenceLayerLocal: this.carFenceLayer,
        videoLayerLocal: this.videoLayer,
        poiSearchStyleRight: '0px',
        currInteraction: {},
        markerFeature: {
          default: undefined
        },
        mapDivLoading: false
      }
    },
    computed: {
      ...mapGetters('topevery', {
        mapOption: 'map/mapOption'
      }),
      mapId() {
        return `map${this.$parent._uid}`
      },
      clickPoiInfo() {
        return Object.assign({
          closePoiList: false,
          showPoiInfo: true,
          showPoiTitle: true
        }, this.clickPoi)
      }
    },
    mounted() {
      this.initMap()
      // this.showMarker()
      this.showMarkerFeature()
      // this.showPoiLayer()
    },
    watch: {
      caseLayer() {

      },
      staffLayer() {

      },
      carLayer() {

      },
      carFenceLayer() {
        this.helper.initWMSLayer('car_electronic_fence', this.carFenceLayer)
      },
      videoLayer() {

      },
      partsLayerCqlFilter() {
        // this.initPartsLayer()
      },
      caseLayerLocal() {
        this.initCaseFeature(this.caseLayerLocal)
      },
      staffLayerLocal() {
        this.initStaffFeature(this.staffLayerLocal)
      },
      carLayerLocal() {
        this.initCarFeature(this.carLayerLocal)
      },
      carFenceLayerLocal() {
        this.helper.initWMSLayer('car_fence', this.carFenceLayerLocal)
      },
      videoLayerLocal() {
        this.initVideoFeature(this.videoLayerLocal)
      },
      wmsIds() {
        this.initLayer()
      }
    },
    methods: {
      handleSearch(e) {
        this.$emit('handleSearch', e)
      },
      switchShow(e) {
        this.$emit('switchShow', e)
      },
      /**
       * @Author yuesheng.zhu@topevery.club
       * @Date 2019/5/9 18:18
       * @Description 初始化地图
       */
      initMap() {
        this.map = new TyMap()
        this.map.createMap(this.mapId)
        this.option = {
          map: this.map.getMap(1, true)
        }
        this.helper = new TyHelper(this.option)
        if ($('.map__poi').length > 0) {
          const toolbarWidth = $('.map__toolbar').length === 0 ? 10 : ($('.map__toolbar').width() + 20)
          this.poiSearchStyleRight = toolbarWidth + 'px'
        }
      },
      /**
       * @Description 开启地图框选回调
       * @Date 2019/12/3 17:23
       * @Author yuesheng.zhu@topevery.club
       */
      startMapSelect() {
        const option = {
          id: 'commonMapSelect',
          type: 'dragBox',
          startDragBoxHandler: () => {
            if (typeof this.startDragBoxHandler === 'function') {
              this.startDragBoxHandler()
            }
          },
          endDragBoxHandler: (extent) => {
            const features = this.map.getMapSelectInfo(extent)
            if (this.defaultSelection) {
              this.handleDefaultSelection(extent, features)
            } else {
              if (typeof this.endDragBoxHandler === 'function') {
                this.endDragBoxHandler(extent, features)
              }
            }
          }
        }
        this.currInteraction = this.helper.createInteraction(option)
      },
      /**
       * @Description 关闭地图框选回调
       * @Date 2019/12/3 17:23
       * @Author yuesheng.zhu@topevery.club
       */
      cancelMapSelect() {
        if (this.defaultSelection) {
          this.handleCloseMapSelection()
        }
        this.helper.removeInteraction('commonMapSelect')
        this.$emit('cancel-map-select')
      },

      /**
       * @Description 点击定位当前坐标
       * @Date 2019/12/3 17:23
       * @Author yuesheng.zhu@topevery.club
       */
      handleCurrentPosition() {
        this.map.getMap().getView().animate({
          center: this.markerPoints[0].coordinates,
          duration: 500
        })
        // this.map.fitByFeatures(this.markerFeature['default'].getFeatures())
      },
      /**
       * @Description 初始化图层
       * @Date 2019/12/3 17:23
       * @Author yuesheng.zhu@topevery.club
       */
      initLayer() {
        console.log('this.wmsIds:', this.wmsIds,)
        this.helper.initWMSLayer(this.wmsIdsType)
        let cqlFilter = ''
        this.wmsIds.map((id, index) => {
          cqlFilter += `"id" == '${id}'${index === this.wmsIds.length - 1 ? '' : ' or '}`
        })
        if (cqlFilter !== '') {
          this.helper.initWMSLayer(this.wmsIdsType, true, cqlFilter, validatenull(this.wmsIdsStyles) ? '' : `${this.mapOption.prefix}:${this.wmsIdsStyles}`)
          if (this.wmsGridData.length > 0) {
            // console.log('common-map-wmsGridData:', this.wmsGridData)
            // const format = new GeoJSON({})
            const features = []
            if (this.eventObject.highlightFeatureLayer === null) {
              this.eventObject.highlightFeatureLayer = new TyFeatureLayer(this.option)
            }
            this.eventObject.highlightFeatureLayer.clear()
            let model = {}
            this.wmsGridData.map((item) => {
              // console.log('this.wmsGridData============>', item)
              if(item!=""){
                try {
                  model = JSON.parse(item)
                }catch (e) {
                }
                const feature = (new GeoJSON({featureProjection: 'EPSG:4326'})).readFeature(item)
                feature.setStyle(this.helper.getLayerStyle(0.3, model.gridName ? model.gridName : '', '',model.gridType ? model.gridType : 0))
                // feature.setStyle(this.helper.getLayerStyle(0.3, item.gridName ? item.gridName : ''))
                this.eventObject.highlightFeatureLayer.addFeature(feature)
                features.push(feature)
              }
            })
          }
        } else {
          if (this.eventObject.highlightFeatureLayer !== null) {
            this.eventObject.highlightFeatureLayer.clear()
          }
        }
      }
    }
  }
</script>

<style lang="scss">
  @import './style/main.scss';

  .ol-scale-line {
    left: 200px;
  }

  .ol-mouse-position {
    right: 30px;
    bottom: 10px;
    top: inherit;
    position: absolute;
    width: auto;
    background-color: rgba(255, 255, 255, 0.8);
    height: 32px;
    font-size: 16px;
    line-height: 32px;
  }

  .ol-overviewmap-box {
    width: 74px !important;
    height: 74px !important;
  }
</style>
